package com.ort.ezcalendar.rest;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.os.AsyncTask;
import android.util.Log;

public class GetEventsTask extends AsyncTask<String, Void, Boolean> {
	private ProgressDialog dialog;
	protected Context applicationContext;

	public GetEventsTask(Context c) {
		applicationContext = c;
		dialog = new ProgressDialog(applicationContext);
	}

	@Override
	protected void onPreExecute() {

		this.dialog = ProgressDialog.show(applicationContext,
				"Accediendo al servicio", "Se estan obteniendo los eventos del usuario", true);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		try {
			String urlConection = "http://192.168.2.4/EzCalendar/ServiceEzCalendar.svc/GetEvents/"
					+ params[0];
//			+ readProperties("connection") + readProperties("get_events")
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(urlConection);
			
			httpGet.setHeader("content-type", "application/json");

			HttpResponse httpResponse = httpClient.execute(httpGet);

			HttpEntity httpEntity = httpResponse.getEntity();
			String stringResponse = EntityUtils.toString(httpEntity);
			JSONObject jsonOnject = new JSONObject(stringResponse);
			
			JSONArray events = jsonOnject.getJSONArray("listEvents");
//			for (JSONObject jsonObject : events.) {
				
//			}
			
			 
//	        if(respStr.equals("true")) {
//				return true;
//			}
			return false;
		} catch (NotFoundException e) {
			Log.e("Error", e.toString());
			return false;
		} catch (Exception e) {
			Log.e("Error", e.toString());
			return false;
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		this.dialog.cancel();
	}
	
	private String readProperties(String key) throws IOException {
		String value = "";
		try {
			Resources resources = applicationContext.getResources();
			AssetManager assetManager = resources.getAssets();
			InputStream inputStream = null;
			inputStream = assetManager.open("conection.properties");
			Properties properties = new Properties();
			properties.load(inputStream);
			value = properties.getProperty(key);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return value;
	}
}
